package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 根据时间区间统计营业额
     *
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //获取时间列表
        List<LocalDate> dateList = getDateList(begin, end);

        //获取对应时间每一天的营业额
        List<Double> turnoverList = new ArrayList<>();
        dateList.forEach(date -> {
            LocalDateTime oneDayBeginTime = LocalDateTime.of(date, LocalTime.MIN);  //一天的开始时间, 即00:00
            LocalDateTime oneDayEndTime = LocalDateTime.of(date, LocalTime.MAX);    //一天的结束时间, 即23:59

            //查询营业额
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);    //订单状态需要为已完成
            map.put("begin", oneDayBeginTime);
            map.put("end", oneDayEndTime);

            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;   //如果某一天没有订单, 需要将营业额设置为0, 不然会返回null
            turnoverList.add(turnover);
        });

        //数据封装
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 根据起止时间计算出对应的时间列表
     *
     * @param begin
     * @param end
     * @return
     */
    private static List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);  //日期计算, 获取指定日期后1天的日期
            dateList.add(begin);
        }

        return dateList;
    }

    /**
     * 根据时间区间统计用户数量
     *
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //获取时间列表
        List<LocalDate> dateList = getDateList(begin, end);

        //统计对应时间每一天的新增用户数和总用户数
        List<Integer> newUserList = new ArrayList<>();      //新增用户数
        List<Integer> totalUserList = new ArrayList<>();    //总用户数

        dateList.forEach(date -> {
            LocalDateTime oneDayBeginTime = LocalDateTime.of(date, LocalTime.MIN);  //一天的开始时间, 即00:00
            LocalDateTime oneDayEndTime = LocalDateTime.of(date, LocalTime.MAX);    //一天的结束时间, 即23:59

            Integer newUser = getUserCount(oneDayBeginTime, oneDayEndTime); //当天新增用户数
            Integer totalUser = getUserCount(null, oneDayEndTime);          //截止当天总用户数

            newUserList.add(newUser);
            totalUserList.add(totalUser);
        });

        //数据封装返回
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    /**
     * 根据时间区间统计用户数量
     *
     * @param beginTime
     * @param endTime
     * @return
     */
    private Integer getUserCount(LocalDateTime beginTime, LocalDateTime endTime) {
        Map map = new HashMap();
        map.put("begin", beginTime);
        map.put("end", endTime);
        return userMapper.countByMap(map);
    }

    /**
     * 根据时间区间统计订单数量
     *
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //获取时间列表
        List<LocalDate> dateList = getDateList(begin, end);

        //每天订单总数集合
        List<Integer> orderCountList = new ArrayList<>();

        //每天有效订单数集合
        List<Integer> validOrderCountList = new ArrayList<>();

        dateList.forEach(date -> {
            LocalDateTime oneDayBeginTime = LocalDateTime.of(date, LocalTime.MIN);  //一天的开始时间, 即00:00
            LocalDateTime oneDayEndTime = LocalDateTime.of(date, LocalTime.MAX);    //一天的结束时间, 即23:59

            //查询每天的总订单数
            Integer orderCount = getOrderCount(oneDayBeginTime, oneDayEndTime, null);

            //查询每天的有效订单数
            Integer validOrderCount = getOrderCount(oneDayBeginTime, oneDayEndTime, Orders.COMPLETED);

            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        });

        //时间区间内的总订单数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();

        //时间区间内的总有效订单数
        Integer totalValidOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        //订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = totalValidOrderCount.doubleValue() / totalOrderCount;
        }

        //数据封装返回
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(totalValidOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 根据时间区间统计指定状态的订单数量
     *
     * @param beginTime
     * @param endTime
     * @param status
     * @return
     */
    private Integer getOrderCount(LocalDateTime beginTime, LocalDateTime endTime, Integer status) {
        Map map = new HashMap();
        map.put("status", status);
        map.put("begin", beginTime);
        map.put("end", endTime);
        return orderMapper.countByMap(map);
    }

    /**
     * 查询指定时间区间内的销量排名top10
     *
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getSalesTop10Statistics(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10(beginTime, endTime);

        //top10菜品套餐名列表
        String nameList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()), ",");

        //top10销量列表
        String numberList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()), ",");

        //数据封装返回
        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }



}
